<template>
  <div id="homePage">
    <!-- 横幅区域 -->
    <div class="banner">
      <h1 class="banner-title">智能协同云图库</h1>
      <p class="banner-subtitle">海量高清图片，智能分类管理</p>
    </div>

    <!-- 搜索框 + 刷新缓存 -->
    <div class="search-bar">
      <a-input-search
        placeholder="搜索你想要的图片"
        v-model:value="searchParams.searchText"
        enter-button="🔍 搜索"
        size="large"
        @search="doSearch"
        class="search-box"
      />
      <!-- 仅管理员可见的刷新缓存按钮 -->
      <a-button
        v-if="isAdmin"
        type="primary"
        size="large"
        @click="refreshCache"
        class="refresh-button"
      >
        🔄 刷新缓存
      </a-button>
      <!-- 智能客服悬浮按钮 -->
      <a-button
        type="primary"
        shape="circle"
        class="ai-button"
        @click="gotoCustomersService"
      >
        <template #icon>
          <MessageOutlined :style="{ fontSize: '24px' }"/>
        </template>
      </a-button>

      <!-- 哄哄模拟器悬浮按钮 -->
      <a-button
        type="primary"
        shape="circle"
        class="ai-button"
        @click="gotoGameService"
      >
        <template #icon>
          <HeartFilled :style="{ fontSize: '24px' }"/>
        </template>
      </a-button>

      <!-- ai智能客服functionCoding悬浮按钮 -->
      <a-button
        type="primary"
        shape="circle"
        class="ai-button"
        @click="gotoCusService"
      >
        <template #icon>
          <CustomerServiceTwoTone :style="{ fontSize: '24px' }"/>
        </template>
      </a-button>


      <!-- RAGPDF悬浮按钮 -->
      <a-button
        type="primary"
        shape="circle"
        class="ai-button"
        @click="gotoPDFService"
      >
        <template #icon>
          <CopyOutlined :style="{ fontSize: '24px' }"/>
        </template>
      </a-button>

    </div>

    <!-- 分类 + 标签 -->
    <div class="category-tag-container">
      <a-tabs
        v-model:activeKey="selectedCategory"
        @change="doSearch"
        class="category-tabs"
        size="large"
      >
      <a-tab-pane key="all" tab="全部" />
      <a-tab-pane
        v-for="category in categoryList"
        :key="category"
        :tab="category"
      />
      </a-tabs>

      <div class="tag-bar">
        <span class="tag-label">标签：</span>
        <a-space :size="[8, 8]" wrap>
          <a-checkable-tag
            v-for="(tag, index) in tagList"
            :key="tag"
            v-model:checked="selectedTagList[index]"
            @change="doSearch"
            class="custom-tag"
          >
            {{ tag }}
          </a-checkable-tag>
        </a-space>
      </div>

      <!-- 按颜色搜索 -->
      <a-form-item label="按颜色搜索" style="margin-top: 16px">
        <color-picker format="hex" @pureColorChange="onColorChange" />
      </a-form-item>

    </div>

    <!-- 图片列表 -->
    <PictureList :dataList="dataList" :loading="loading" />
    <div class="pagination-container">
      <a-pagination
        :current="searchParams.current"
        :page-size="searchParams.pageSize"
        :total="total"
        :show-size-changer="true"
        @change="onPageChange"
      />
    </div>

    <!-- 在首页模板末尾添加 -->
    <div class="customer-service-icon" @click="gotoCustomerService">
      <!-- 或使用图片 -->
      <img src="@/assets/客服 (1).png" alt="智能客服">
    </div>

  </div>
</template>

<script setup lang="ts">
import { computed, onMounted, reactive, ref } from 'vue'
import {
  listPictureTagCategoryUsingGet,
  listPictureVoByPageUsingPost, listPictureVoByPageWithCacheUsingPost,
  refreshPictureCacheUsingPost, searchAllPictureByColorUsingPost
} from '@/api/pictureController.ts'
import { message } from 'ant-design-vue'
import { useRouter } from 'vue-router'
import { useLoginUserStore } from '@/stores/useLoginUserStore.ts'
import { storeToRefs } from 'pinia'
import 'lazysizes/plugins/attrchange/ls.attrchange'
import 'lazysizes';
import PictureList from '@/components/PictureList.vue'
import { ColorPicker } from 'vue3-colorpicker'
import { MessageOutlined,HeartFilled,CustomerServiceTwoTone,CopyOutlined } from '@ant-design/icons-vue'

// 数据
const dataList = ref([])
const total = ref(0)
const loading = ref(true)

// 搜索条件
const searchParams = reactive<API.PictureQueryRequest>({
  current: 1,
  pageSize: 20,
  sortField: 'createTime',
  sortOrder: 'descend',
})

// 分页参数
const pagination = computed(() => {
  return {
    current: searchParams.current ?? 1,
    pageSize: searchParams.pageSize ?? 10,
    total: total.value,
    // 切换页号时，会修改搜索参数并获取数据
    onChange: (page:number, pageSize:number) => {
      searchParams.current = page
      searchParams.pageSize = pageSize
      fetchData()
    },
  }
})
const gotoCustomerService = () => {
  // 如果需要新窗口打开
  const routeUrl = router.resolve({ path: '/user_AI' })
  window.open(routeUrl.href, '_blank')
}

const gotoCustomersService = () => {
  // 如果需要新窗口打开
  const routeUrl = router.resolve({ path: '/user_AISpring' })
  window.open(routeUrl.href, '_blank')
}

const gotoGameService = () => {
  // 如果需要新窗口打开
  const routeUrl = router.resolve({ path: '/user_AIGAME' })
  window.open(routeUrl.href, '_blank')
}

const gotoCusService = () => {
  // 如果需要新窗口打开
  const routeUrl = router.resolve({ path: '/user_AIService' })
  window.open(routeUrl.href, '_blank')
}

const gotoPDFService = () => {
  // 如果需要新窗口打开
  const routeUrl = router.resolve({ path: '/user_AIPDF' })
  window.open(routeUrl.href, '_blank')
}

// 获取数据
const fetchData = async () => {
  loading.value = true
  const params = {
    ...searchParams,
    tags: [],
  }
  if (selectedCategory.value !== 'all') {
    params.category = selectedCategory.value
  }
  selectedTagList.value.forEach((useTag, index) => {
    if (useTag) {
      params.tags.push(tagList.value[index])
    }
  })
  const res = await listPictureVoByPageWithCacheUsingPost(params)
  if (res.data.data) {
    dataList.value = res.data.data.records ?? []
    total.value = res.data.data.total ?? 0  // ⚠️ 确保 total 赋值
  } else {
    message.error('获取数据失败，' + res.data.message)
  }
  loading.value = false
}

const onColorChange = async (color: string) => {
  const res = await searchAllPictureByColorUsingPost({
    picColor: color,
  })
  if (res.data.code === 0 && res.data.data) {
    const data = res.data.data ?? [];
    dataList.value = data;
    total.value = data.length;
  } else {
    message.error('获取数据失败，' + res.data.message)
  }
}


// 页面加载时请求一次
onMounted(() => {
  fetchData()
})

const doSearch = () => {
  // 重置搜索条件
  searchParams.current = 1
  fetchData()
}

const categoryList = ref<string[]>([])
const selectedCategory = ref<string>('all')
const tagList = ref<string[]>([])
const selectedTagList = ref<string[]>([])

// 获取标签和分类选项
const getTagCategoryOptions = async () => {
  const res = await listPictureTagCategoryUsingGet()
  if (res.data.code === 0 && res.data.data) {
    // 转换成下拉选项组件接受的格式
    categoryList.value = res.data.data.categoryList ?? []
    tagList.value = res.data.data.tagList ?? []
  } else {
    message.error('加载分类标签失败，' + res.data.message)
  }
}

onMounted(() => {
  getTagCategoryOptions()
})

const router = useRouter()

// 跳转至图片详情
const doClickPicture = (picture) => {
  router.push({
    path: `/picture/${picture.id}`,
  })
}

const onPageChange = (page, pageSize) => {
  searchParams.current = page
  searchParams.pageSize = pageSize
  fetchData()
}

const refreshCache = async () => {
  try {
    const res = await refreshPictureCacheUsingPost(searchParams);
    if (res.data.code === 0) {
      message.success("缓存刷新成功！");
    } else {
      message.error(res.data.message || "刷新缓存失败");
    }
  } catch (error) {
    console.error("刷新缓存失败", error);
    message.error("刷新缓存失败，请稍后再试");
  }
};


const loginUserStore = useLoginUserStore()
const { isAdmin } = storeToRefs(loginUserStore)

// 组件加载时获取用户信息
loginUserStore.fetchLoginUser()


</script>

<style scoped>

.customer-service-icon img {
  width: 40px;  /* 调整目标尺寸 */
  height: 40px;
  object-fit: contain;  /* 保持图片比例不变形[4](@ref) */
}

/* 父容器同步缩小 */
.customer-service-icon {
  width: 50px;  /* 原60px改为50px */
  height: 50px; /* 原60px改为50px */
  right: 30px;  /* 调整右侧间距 */
  bottom: 60px;  /* 调整底部间距 */
}
/* 页面整体背景 */
#homePage {
  background: linear-gradient(to bottom, #f0f2f5, #ffffff);
  padding-bottom: 32px;
}

/* 横幅区域 */
.banner {
  text-align: center;
  padding: 60px 20px;
  background: url(https://imgpp.ztupic.com/topicbanner/1741570195680_3a4d4607.jpg?x-oss-process=image/sharpen,100) center/cover no-repeat;
  color: white;
  font-weight: bold;
  box-shadow: 0px 4px 10px rgba(0, 0, 0, 0.1);
}

.banner-title {
  font-size: 36px;
  margin-bottom: 8px;
  text-shadow: 2px 2px 5px rgba(0, 0, 0, 0.2);
}

.banner-subtitle {
  font-size: 18px;
  opacity: 0.8;
}

/* 搜索框 */
.search-bar {
  display: flex;
  justify-content: center;
  margin: 20px 0;
}

.search-box {
  width: 600px;
  border-radius: 25px;
}

/* 分类导航 */
.category-tabs {
  margin-bottom: 16px;
}

/* 标签区域 */
.tag-bar {
  text-align: center;
  margin-bottom: 16px;
}

.tag-label {
  font-size: 16px;
  font-weight: bold;
}

.custom-tag {
  border-radius: 15px;
  padding: 6px 12px;
  transition: all 0.3s ease-in-out;
}

.custom-tag:hover {
  transform: scale(1.1);
  background: #1890ff;
  color: white !important;
}


.picture-card:hover .picture-image {
  transform: scale(1.1);
}

.picture-card:hover .picture-overlay {
  opacity: 1;
}

.overlay-tags .ant-tag {
  background: rgba(255, 255, 255, 0.3);
  border: none;
  color: white;
}

.pagination-container {
  display: flex;
  justify-content: flex-end; /* 将内容向右对齐 */
  margin: 20px 0; /* 可选，添加上下间距 */
}

.category-tag-container {
  margin: 20px 0; /* 顶部和底部间距 */
  padding: 20px; /* 内部填充 */
  background: #ffffff; /* 背景颜色 */
  border-radius: 8px; /* 圆角 */
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1); /* 阴影效果 */
}

.category-tabs {
  margin-bottom: 16px; /* 分类标签和标签之间的间距 */
}

/* 标签区域样式 */
.tag-bar {
  display: flex;
  align-items: center; /* 垂直居中 */
  flex-wrap: wrap; /* 标签换行 */
  margin-top: 10px; /* 上边距 */
}

.tag-label {
  font-size: 16px; /* 标签文字大小 */
  font-weight: bold; /* 加粗 */
  margin-right: 10px; /* 标签与标签之间的间距 */
}

.custom-tag {
  border-radius: 15px; /* 圆角 */
  padding: 6px 12px; /* 内部填充 */
  transition: background-color 0.3s, transform 0.3s; /* 动画效果 */
}

.custom-tag:hover {
  background: #1890ff; /* 悬停时的背景颜色 */
  color: white !important; /* 悬停时的文字颜色 */
  transform: scale(1.05); /* 悬停时放大效果 */
}
.search-bar {
  display: flex;
  align-items: center;
  gap: 16px; /* 设置按钮间距 */
}
/* 固定定位样式 */
.customer-service-icon {
  position: fixed;
  right: 40px;
  bottom: 80px;
  z-index: 999;
  width: 60px;
  height: 60px;
  border-radius: 50%;
  background: #1890ff;
  box-shadow: 0 4px 12px rgba(24, 144, 255, 0.4);
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.3s ease-in-out;
}

.customer-service-icon:hover {
  transform: scale(1.1);
  box-shadow: 0 6px 16px rgba(24, 144, 255, 0.6);
}

.icon {
  font-size: 28px;
  color: white;
}
</style>
